﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data.Common;
using System.Configuration;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.ConversionTools;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.AnalysisTools;

namespace WindowsApplication1
{
    public partial class 数据导出 : Form
    {
        public 数据导出()
        {
            InitializeComponent();
        }
        public void InitTree(Hashtable jiedao2shequ)
        {
            foreach (string jiedaoname in jiedao2shequ.Keys)
            {
                TreeNode node = new TreeNode(jiedaoname);
                node.Checked = false;
                List<WindowsApplication1.Form1.NameAndGeometry> shequs = jiedao2shequ[jiedaoname] as List<WindowsApplication1.Form1.NameAndGeometry>;
                foreach (WindowsApplication1.Form1.NameAndGeometry shequ in shequs)
                {
                    node.Nodes.Add(shequ.ToString()).Checked = false;
                }
                treeView1.Nodes.Add(node);
            }
        }

        bool oncheckevent = false;
        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
        {
            if (oncheckevent)
                return;
            oncheckevent = true;
            if (e.Node.Checked)
            {
                if (e.Node.Parent != null)
                    e.Node.Parent.Checked = true;
                else
                {
                    foreach (TreeNode node in e.Node.Nodes)
                    {
                        node.Checked = true;
                    }
                }
            }
            else
            {
                if (e.Node.Parent == null)
                {
                    foreach (TreeNode node in e.Node.Nodes)
                    {
                        node.Checked = false;
                    }
                }
                else
                {
                    e.Node.Parent.Checked = false;
                    foreach (TreeNode node in e.Node.Parent.Nodes)
                    {
                        if (node.Checked)
                        {
                            node.Parent.Checked = true;
                            break;
                        }
                    }
                }
            }
            oncheckevent = false;
        }
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string jiedaonames = "";
                string shequnames = "";
                foreach (TreeNode node in treeView1.Nodes)
                {
                    if (node.Checked)
                    {
                        jiedaonames += "'" + node.Text + "',";
                    }
                    foreach (TreeNode shequnode in node.Nodes)
                    {
                        if (shequnode.Checked)
                        {
                            shequnames += "'" + shequnode.Text + "',";
                        }
                    }
                }
                jiedaonames = jiedaonames.TrimEnd(',');
                shequnames = shequnames.TrimEnd(',');
                if (jiedaonames == "" || shequnames == "")
                {
                    MessageBox.Show("请选择社区或街道");
                    return;
                }
                string fromconnstr = "Data Source=(DESCRIPTION =    (ADDRESS = (PROTOCOL = TCP)(HOST = {0})(PORT = 1521))    (CONNECT_DATA =      (SERVER = DEDICATED)      (SERVICE_NAME = orcl)    )  );User ID={1};Password={2}";
                fromconnstr = string.Format(fromconnstr, this.textBox1.Text, textBox2.Text, textBox3.Text);
                DbConnection conn2 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, fromconnstr);
                try
                {
                    conn2.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\r\n" + "打开" + textBox1.Text + "数据库失败!");
                    return;
                }
                finally
                {
                    conn2.Close();
                }
                DbConnection conn1 = Form1.CreateDbConnection(ConfigurationManager.ConnectionStrings["conn"].ProviderName, ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
                try
                {
                    conn1.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
                DbCommand command = conn1.CreateCommand();
                command.CommandText = "select " + Settings.社区编号 + " from " + Settings.社区图层 + " t where t." + Settings.社区名称 + " in (" + shequnames + ")";
                DbDataReader reader = command.ExecuteReader();
                shequnames = "";
                while (reader.Read())
                {
                    shequnames += "'" + reader.GetString(0) + "',";
                }
                shequnames = shequnames.TrimEnd(',');

                reader.Close();
                
                conn1.Close();
                IWorkspaceFactory fac = new SdeWorkspaceFactoryClass() as IWorkspaceFactory;
                IPropertySet pset = new PropertySetClass();
                pset.SetProperty("Server", textBox1.Text);
                pset.SetProperty("Instance", "5151");
                pset.SetProperty("user", textBox2.Text);
                pset.SetProperty("password", textBox3.Text);
                pset.SetProperty("Database", "");
                pset.SetProperty("version", "sde.DEFAULT");
                string folder = @"c:\";
                string filename = @"ddd.sde";
                if (System.IO.File.Exists(folder + filename))
                {
                    try
                    {
                        System.IO.File.Delete(folder + filename);
                    }
                    catch { }
                }
                fac.Create(folder, filename, pset, 0);
                textBox7.Text = "";
                textBox7.ScrollBars = ScrollBars.Both;
                textBox7.WordWrap = false;
                Geoprocessor pro = new Geoprocessor();
                string folder1 = "c:\\";
                string filename1 = "aaa.sde";
                if (System.IO.File.Exists(folder1 + filename1))
                {
                    System.IO.File.Delete(folder1 + filename1);
                }
                fac = ((IDataset)Form1.建筑图层.FeatureClass).Workspace.WorkspaceFactory;
                fac.Create(folder1, filename1, ((IDataset)Form1.建筑图层.FeatureClass).Workspace.ConnectionProperties, 0);
                
                //创建建筑图层
                string fcname = Form1.建筑图层.Name;
                MakeFeatureLayer makefeaturelayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + fcname, fcname);
                makefeaturelayer.where_clause = "substr(" + Settings.建筑编号 + ",0,12) in (" + shequnames + ")";
                pro.Execute(makefeaturelayer, null);
                
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建完毕，将图层中的数据拷贝到目标数据库中
                CopyFeatures copyfeatures = new CopyFeatures(fcname, folder + filename + "\\" + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyfeatures, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建用电建筑图层
                fcname = Form1.用电建筑图层.Name;
                makefeaturelayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + fcname, fcname);
                makefeaturelayer.where_clause = "substr(" + Settings.用电建筑编号 + ",0,12) in (" + shequnames + ")";
                pro.Execute(makefeaturelayer, null);

                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建完毕，将图层中的数据拷贝到目标数据库中
                copyfeatures = new CopyFeatures(fcname, folder + filename + "\\" + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyfeatures,null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建街道图层
                fcname = Form1.街道图层.Name;
                makefeaturelayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + fcname, fcname);
                makefeaturelayer.where_clause = Settings.街道名称 + " in (" + jiedaonames + ")";
                pro.Execute(makefeaturelayer, null);

                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建完毕，将图层中的数据拷贝到目标数据库中
                copyfeatures = new CopyFeatures(fcname, folder + filename + "\\" + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyfeatures, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建社区图层
                fcname = Form1.社区图层.Name;
                makefeaturelayer = new MakeFeatureLayer(folder1 + filename1 + "\\" + fcname, fcname);
                makefeaturelayer.where_clause = Settings.社区编号 + " in (" + shequnames + ")";
                pro.Execute(makefeaturelayer, null);

                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建完毕，将图层中的数据拷贝到目标数据库中
                copyfeatures = new CopyFeatures(fcname, folder + filename + "\\" + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyfeatures, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                //创建用电建筑信息表
                fcname = Settings.用电建筑信息;

                MakeTableView makequerytable = new MakeTableView(folder1 + filename1 + "\\" + fcname, fcname);
                makequerytable.where_clause = "substr(" + Settings.用电建筑编号 + ",0,12) in (" + shequnames + ")";
                pro.Execute(makequerytable,null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                CopyRows copyrows = new CopyRows(fcname, folder + filename + "\\" + textBox2.Text + "." + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyrows,null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                fcname = "建筑编码2电力户号";
                makequerytable = new MakeTableView(folder1 + filename1 + "\\" + fcname, fcname);
                makequerytable.where_clause = "substr(" + Settings.用电建筑编号 + ",0,12) in (" + shequnames + ")";
                pro.Execute(makequerytable, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                copyrows = new CopyRows(fcname, folder + filename + "\\" + textBox2.Text + "." + fcname);
                pro.OverwriteOutput = true;
                pro.Execute(copyrows, null);
                for (int i = 0; i < pro.MessageCount; i++)
                {
                    textBox7.Text += pro.GetMessage(i).Replace('\r', ' ').Replace('\n', ' ');
                    textBox7.Text += "\r\n";
                }
                MessageBox.Show("数据导出完成！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }
    }
}
